package com.bank.lenovoz5;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.RemoteException;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.StaleObjectException;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.util.Log;

import com.entity.BankOrder;
import com.entity.User;
import com.receive.SMSReceiverSend;
import com.receive.USBReceiver;
import com.show.api.util.StringUtils;
import com.utils.ChatClient;
import com.utils.Constants;
import com.utils.FileHelper;
import com.utils.ImageView;
import com.utils.LogToFile;
import com.utils.XunFeiConfig;

import java.text.DecimalFormat;

import static android.os.SystemClock.sleep;
import static com.utils.ChatClient.C_updateBalance_W;
import static com.utils.ChatClient.ConfirmOrder;
import static com.utils.ChatClient.addWorkTime;
import static com.utils.ChatClient.getSerialNumber;
import static com.utils.ChatClient.getmap;
import static com.utils.ChatClient.list;
import static com.utils.ChatClient.mapDelete;
import static com.utils.ChatClient.userInfo;

/**
 * 项目名称：yzf
 * 类描述：华夏银行提款脚本，不能ROOT
 * 创建人：罗浩
 * 创建时间：2019/3/17 14:13
 * 修改人：罗浩
 * 修改时间：2019/3/17 14:13
 * 修改备注：
 */
public class Z5HXBbank {
    private final String bankName = "华夏银行";
    private UiDevice mDevice;
    SMSReceiverSend sMSReceiverSend;
    static Context context = InstrumentationRegistry.getTargetContext();
    static User user;
    private boolean isChangeBill = false;//是否查账

    private static int[][] xy_123 = new int[][]{
            {180, 1550}, {540, 1550}, {900, 1550},
            {180, 1700}, {540, 1700}, {900, 1700},
            {180, 1865}, {540, 1865}, {900, 1865},
            {540, 2015}, {180, 2015}};

    private static int[][] login_key_xy = new int[][]{
            {55, 1580}, {160, 1580}, {270, 1580}, {380, 1580}, {485, 1580}, {590, 1580}, {700, 1580}, {805, 1580}, {915, 1580}, {1025, 1580},
            {55, 1730}, {160, 1730}, {270, 1730}, {380, 1730}, {485, 1730}, {590, 1730}, {700, 1730}, {805, 1730}, {915, 1730}, {1025, 1730},
            {105, 1880}, {215, 1880}, {320, 1880}, {430, 1880}, {540, 1880}, {645, 1880}, {755, 1880}, {860, 1880}, {970, 1880},
            {215, 2015}, {320, 2015}, {430, 2015}, {540, 2015}, {645, 2015}, {755, 2015}, {860, 2015}
    };

    private static int[] logingTableAbc2Char = {80, 2015};

    private static String bankname = "HXB";
    private static String sumMoney = "0.0";
    private boolean testMode = false;//测试模式识别键盘手动输入
    private int isNextSMS = 1;
    private String carrier;//机型


    public Z5HXBbank(UiDevice mDevice) throws UiObjectNotFoundException {
        this.mDevice = mDevice;
        carrier = android.os.Build.MODEL;
        demo();
    }

    private void demo() throws UiObjectNotFoundException {
        Constants.getsTheModelAndVersionNumberAndVersionName(context, bankName);
        ImageView.saveImg("");
        //启动银行app
        UiObject x = mDevice.findObject(new UiSelector().text("华夏银行"));
        showMsg("点击华夏银行");
        x.click();
        //动态注册短信广播
        Constants.MOBILE_BOB = "95566";
        Constants.MOBILE_BOB_86 = "+8695566";
        sMSReceiverSend = new SMSReceiverSend();
        Constants.CODE = "";
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.SMS_ACTION);
        filter.addAction("net.blogjava.mobile.SMSto");
        // 设置优先级 不然监听不到短信
        filter.setPriority(1000);
        context.registerReceiver(sMSReceiverSend, filter);
        Intent intent = new Intent();
        intent.setAction("com.tiantian.SEND_TO");
        context.sendBroadcast(intent);
        //检查usb连接状态
        while (true) {
            if (Constants.STATE_USB) {
                sleep(ChatClient.overtime_15);
                homeTransfer();
                break;
            }
        }
    }

    //检索转账：进入转账
    public void homeTransfer() throws UiObjectNotFoundException {
        showMsg("进入主页");
        closeRechargeDialog();
        //连接服务端
        ChatClient.start();

        while (true) {
            UiObject mTV_transfer = mDevice.findObject(new UiSelector().text("转账").resourceId("com.yt" +
                    ".hxmb50.launcher:id/item_bank_top_menu_tv_name"));
            if (mTV_transfer != null && mTV_transfer.exists()) {
                showMsg("点击主页转账");
                mTV_transfer.click();
                break;
            }
        }
        sleep(ChatClient.overtime_2);
        //获取账号信息
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime1 = System.currentTimeMillis();
            if ((nowtime1 - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(LogToFile.getMethodName(), "登陆超时");
                return;
            }
            //请求登录信息
            if (userInfo.equals("")) {
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_GET_BANK_LOGIN_INFO_P +
                        "'}</YZF>");
                sleep(5000);
            } else {
                user = new User();
                String[] res = userInfo.split(" ");
                user.setUserName(res[0]);
                user.setPwd(res[1]);
                user.setBankpwd(res[2]);
                user.setUseType(res[4]);
                user.setBankId(res[5]);
                break;
            }
        }
        sleep(2000);
        Login();
    }

    /**
     * 关闭主页广告等提示
     */
    private void closeRechargeDialog() {
        // 充值对话框
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        try {
            while (true) {
                long nowtime = System.currentTimeMillis();
                if ((nowtime - ChatClient.begintime) > ChatClient.overtime_10) {
                    showMsg("dialog超时");
                    return;
                }
                UiObject mTV = mDevice.findObject(new UiSelector().resourceId("com.yt.shareres:id/rightOkTV").text("知道了"));
                UiObject mTV_update = mDevice.findObject(new UiSelector().resourceId("com.yt.shareres:id/dialog_update_tv_cancel"));
                if (mTV.exists()) {
                    showMsg("关闭温馨提示");
                    mTV.click();
                }
                if (mTV_update.exists()) {
                    showMsg("关闭更新提示");
                    mTV_update.click();
                }
            }
        } catch (StaleObjectException exceptio) {
            showMsg("查找充值对话框dialog错误");
            closeRechargeDialog();
        } catch (UiObjectNotFoundException e) {
            e.printStackTrace();
        }
    }

    //进入登录页面补充用户信息
    public void Login() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_60) {
                String errStr = "登录页面超时";
                showMsg(errStr);
                ChatClient.timer(LogToFile.getMethodName(), errStr);
                return;
            }
            UiObject phonePwdKeys = mDevice.findObject(new UiSelector().text("华夏银行安全输入").className("android.widget.TextView"));
            UiObject phonePwd = mDevice.findObject(new UiSelector().text("登录密码").resourceId("com.yt.hxmb50.launcher:id/et_password"));
            if (!phonePwdKeys.exists() && phonePwd.exists()) {
                showMsg("弹出键盘");
                phonePwd.click();
                sleep(ChatClient.overtime_2);
            } else {
                /********输入密码**********/
                showMsg("填充登录密码phonePwd");
                for (char c : user.getPwd().toCharArray()) {
                    showMsg("输入+1");
                    wantScreenshot(c);//便利密码单独字符传入点击
                    sleep(ChatClient.overtime_1);
                }
                break;
            }
        }
        while (true) {
            UiObject mTV_carry_out = mDevice.findObject(new UiSelector().resourceId("com.yt.hxmb50.launcher:id/okTV").text("完成"));
            if (mTV_carry_out.exists()) {
                showMsg("收起键盘");
                mTV_carry_out.click();
                sleep(ChatClient.overtime_1);
            }
            UiObject login = mDevice.findObject(new UiSelector().text("登录").resourceId("com.yt.hxmb50.launcher:id/btn_login"));
            if (login.exists()) {
                showMsg("点击登录login");
                login.click();
                sleep(ChatClient.overtime_5);
                break;

            }
        }
        /****************上报T端登陆成功*********************/
        while (true) {
            UiObject zhuanzhang = mDevice.findObject(new UiSelector().text("新收款人").className("android.view.View"));
            if (zhuanzhang != null && zhuanzhang.exists()) {
                ChatClient.loginS();
                break;
            }
        }
        setTimerun();
    }

    boolean is_lower_case = true;//是小写键盘

    /**
     * 判定是输入大小写
     */
    private void wantScreenshot(char c) {
        if (Character.isLowerCase(c) != is_lower_case) {
            showMsg("切换键盘大小写");
            mDevice.click(logingTableAbc2Char[0], logingTableAbc2Char[1]);
            is_lower_case = !is_lower_case;
            sleep(ChatClient.overtime_1);
        }
        String key = "";
        if (!Character.isLowerCase(c)) {
            key = String.valueOf(c).toLowerCase();
            c = key.toCharArray()[0];
        }

        char[] keys = "1234567890qwertyuiopasdfghjklzxcvbnm".toCharArray();
        for (int i = 0; i < keys.length; i++) {
            if (keys[i] == c) {
                mDevice.click(login_key_xy[i][0], login_key_xy[i][1]);
            }
        }
    }


    /**
     * 不断进入跨行汇款，等待订单
     *
     * @throws UiObjectNotFoundException
     */
    public void setTimerun() throws UiObjectNotFoundException {
        while (true) {
            sleep(ChatClient.overtime_3);
            if (ChatClient.existOrder()) {
                if (ConfirmOrder) {
                    //查账
                    isChangeBill = true;
                    showMsg("有订单，准备进入查账");
                    getBalanceBack();
                    auditOrder();
                } else {
                    //开始转账
                    isChangeBill = false;
                    showMsg("有订单，准备进入转账");
                    getBalanceBack();
                    transfer();
                }
            } else {
                isChangeBill = false;
                showMsg("没有订单,等待订单");
                /************向T端请求订单*****************/
                getBalanceBack();
            }
        }
    }


    /**
     * 返回转账主页
     *
     * @throws UiObjectNotFoundException
     */
    private void getBalanceBack() throws UiObjectNotFoundException {
        getBalance();
        if (!ChatClient.waitExistOrder(ChatClient.overtime_60)) {
            backTransferHome();
        }
    }

    /**
     * 检测余额
     *
     * @throws UiObjectNotFoundException
     */
    private boolean getBalance() throws UiObjectNotFoundException {
        showMsg("检测余额");
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_20) {
                showMsg("当前余额未找到，退出在次查询");
                mDevice.pressBack();
                ChatClient.addWorkTime(ChatClient.overtime_30);
                sleep(ChatClient.overtime_5);
                getBalanceBack();
                return false;
            }
            UiObject zhuanzhang = mDevice.findObject(new UiSelector().text("新收款人").className("android.view.View"));
            if (zhuanzhang.exists()) {
                showMsg("点击新收款人");
                zhuanzhang.click();
                sleep(ChatClient.overtime_2);
            }
            UiObject object = mDevice.findObject(new UiSelector().className("android.webkit.WebView").index(0));
            UiObject object1 = object.getChild(new UiSelector().className("android.view.View").index(11));
            if (object1.exists()) {
                UiObject mV_money_layout = object1.getChild(new UiSelector().index(1).className("android.view.View"));
                UiObject mV_money = mV_money_layout.getChild(new UiSelector().index(1).className("android.view.View"));
                if (mV_money.exists()) {
                    String money = mV_money.getText();
                    if (money.equals("")) {
                        money = mV_money.getContentDescription();
                    }
                    String[] moneys = money.split("¥");
                    if (!StringUtils.isEmpty(moneys[0])) {
                        sumMoney = moneys[1];
                        showMsg("===检测到余额为：==" + sumMoney);
                        C_updateBalance_W(Double.parseDouble(sumMoney));
                        if (!isChangeBill) {
                            showMsg("本地保存余额");
                            String sumMoneyFile = user.getUserName() + bankname + "_sumMoney.txt";
                            FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
                        }
                        return true;
                    }
                }
            }
        }
    }

    /**
     * 在订单状态未知情况下查账
     */
    public void auditOrder() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_60);
        sleep(ChatClient.overtime_3);
        BankOrder bankOrder = list.get(0);
        /*****************默认查当天账单************************/
        while (true) {
            UiObject mIV = mDevice.findObject(new UiSelector().resourceId("com.yt.hxmb50.launcher:id/right_image").index(0));
            if (mIV.exists()) {
                showMsg("点击转账记录");
                mIV.click();
                break;
            }
        }
        sleep(ChatClient.overtime_5);
        while (true) {
            UiObject mTV = mDevice.findObject(new UiSelector().resourceId("com.yt.hxmb50.launcher:id/middleTextTV").text("转账记录查询"));
            if (mTV.exists()) {
                showMsg("以进入转账查询列表");
                break;
            }
        }
        String name = "", money = "", bankNo = "";
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_15) {
                String errStr = "条目查找失败";
                showMsg(errStr);
                poseTOrderResult(money, name, bankNo);
                return;
            }
            UiObject mV_item = mDevice.findObject(new UiSelector().resourceId("dataList").index(1));
            if (mV_item.exists()) {
                UiObject mV_name_layout = mV_item.getChild(new UiSelector().className("android.view.View").index(1));
                UiObject mV = mV_name_layout.getChild(new UiSelector().className("android.view.View").index(1));
                UiObject mV1 = mV.getChild(new UiSelector().className("android.view.View").index(1));
                UiObject mV_name = mV1.getFromParent(new UiSelector().className("android.view.View").index(0));
                if (mV_name.exists()) {
                    name = mV_name.getText();
                }
                UiObject mV_money_layout = mV_item.getChild(new UiSelector().className("android.view.View").index(3));
                UiObject mV_money = mV_money_layout.getChild(new UiSelector().className("android.view.View").index(0));
                if (mV_money.exists()) {
                    money = mV_money.getText();
                    money = money.replaceAll("-", "");
                    money = money.replaceAll(",", "");
                }
                if (name.equals(bankOrder.getUserName()) && Double.parseDouble(money) == Double.parseDouble(bankOrder.getMoney())) {
                    showMsg("name =" + name + ", money = " + money);
                    showMsg("点击条目一");
                    mV_name_layout.click();
                    sleep(ChatClient.overtime_3);
                    break;
                } else {
                    if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(name)) {
                        String errStr = "条目查找不吻合";
                        showMsg(errStr);
                        poseTOrderResult(money, name, bankNo);
                        return;
                    }
                }
            }
        }

        while (true) {
            UiObject mTV_title = mDevice.findObject(new UiSelector().resourceId("com.yt.hxmb50.launcher:id/middleTextTV").text("记录详情"));
            if (mTV_title.exists()) {
                showMsg("以跳转到记录详情页");
                UiObject mWV = mDevice.findObject(new UiSelector().className("android.webkit.WebView").index(0));
                if (mWV.exists()) {
                    UiObject mTV_bankNo = mWV.getChild(new UiSelector().className("android.view.View").index(6));
                    if (mTV_bankNo.exists()) {
                        bankNo = mTV_bankNo.getText().trim();
                        showMsg("获取到账单银行号：" + bankNo.substring(bankNo.length() - 4, bankNo.length()));
                        break;
                    }
                }
            }
        }
        sleep(1000);
        poseTOrderResult(money, name, bankNo);
    }

    /**
     * 上报查询的订单信息
     *
     * @param money
     * @param name
     * @param bankNo
     */
    private void poseTOrderResult(String money, String name, String bankNo) {
        BankOrder bankOrder = list.get(0);
        String json = "";
        String mobileD = "";
        String moery1 = "0";
        String orderbankNo = "";
        String bankNoTail = "";
        if (!StringUtils.isEmpty(money)) {
            moery1 = money.replaceAll("-", "");
        }
        if (!StringUtils.isEmpty(name)) {
            name = name.trim();
        }
        if (!StringUtils.isEmpty(bankNo)) {
            orderbankNo = bankOrder.getBankNo().substring(bankOrder.getBankNo().length() - 4, bankOrder.getBankNo().length());
            bankNoTail = bankNo.substring(bankNo.length() - 4, bankNo.length());
        }
        showMsg("数据比较===》" + "money:" + (Double.parseDouble(bankOrder.getMoney()) == Double.parseDouble(moery1)) + "---name:" + bankOrder
                .getUserName()
                .equals(name) + "---bankNo:" + orderbankNo.equals(bankNoTail));
        if (Double.parseDouble(bankOrder.getMoney()) == Double.parseDouble(moery1) && bankOrder.getUserName().equals(name) && orderbankNo
                .equals(bankNoTail)) {
            showMsg("查询交易成功");
            json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':0,'type':1";
            mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'华夏银行'," +
                    "'info':'转账成功'";
        } else {
            String sumMoneyFile = user.getUserName() + bankname + "_sumMoney.txt";
            String oldMoney = FileHelper.readSDFile(sumMoneyFile);
            switch (Constants.changeInAmount(bankname, oldMoney, sumMoney, list.get(0).getMoney())) {
                case "0":
                    json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':0,'type':1";
                    mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'华夏银行'," +
                            "'info':'交易成功'";
                    break;
                case "1":
                    json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':1,'type':1";
                    mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'华夏银行'," +
                            "'info':'交易待处理...'";
                    break;
                case "4":
                    json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':4,'type':1";
                    mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'华夏银行'," +
                            "'info':'未查到条目'";
                    break;
            }
        }
        ChatClient.msg("<YZF>{'header':'" + ChatClient.S_CONFIRM_TRADE_RESULT_C + "'," + json + "," + mobileD + "}</YZF>");
        mapDelete(list.get(0).getOrder());
        getmap();
        showMsg("返回上层");
        mDevice.pressBack();
    }


    /**
     * 转账
     *
     * @throws UiObjectNotFoundException
     */
    public void transfer() throws UiObjectNotFoundException {
        if (Double.parseDouble(sumMoney) < Double.parseDouble(list.get(0).getMoney())) {
            String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT +
                    "','phoneModel':'华夏银行'," +
                    "'info':'账户余额不足'";
            String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':1,'type':1";
            ChatClient.msg("<YZF>{'header':'" + ChatClient.M_SEND_TRADE_RESULT_P + "'," + json +
                    "," + mobileD + "}</YZF>");
            showMsg("余额不足:" + sumMoney);
            //删除处理过的订单
            mapDelete(list.get(0).getOrder());
            getmap();
            backTransferHome();
            sleep(ChatClient.overtime_3);
            return;
        }
        crossRowTransfer();
    }


    /**
     * 汇款信息
     */
    private void crossRowTransfer() throws UiObjectNotFoundException {
        BankOrder bankOrder = list.get(0);
        /*******汇款账单信息填充页面*********/
        while (true) {
            UiObject uiObject = mDevice.findObject(new UiSelector().resourceId("demo-input-1").className("android.widget.EditText"));
            if (uiObject.exists()) {
                showMsg("填入收款人名");
                uiObject.setText(bankOrder.getUserName());
                break;
            }
        }
        sleep(2000);
        while (true) {
            UiObject uiObject = mDevice.findObject(new UiSelector().resourceId("demo-input-2").className("android.widget.EditText"));
            if (uiObject.exists()) {
                showMsg("填入银行卡号");
                uiObject.setText(bankOrder.getBankNo());
                sleep(ChatClient.overtime_1);
                uiObject.longClick();
                break;
            }
        }
        sleep(ChatClient.overtime_3);
        if (selectBank()) {
            sleep(2000);
            putMoney();
            while (true) {
                UiObject uiObject = mDevice.findObject(new UiSelector().text("确认").className("android.widget.Button"));
                if (uiObject.exists()) {
                    showMsg("点击跨行汇款中确认");
                    uiObject.click();
                    break;
                }
            }
            sleep(ChatClient.overtime_1);
            isNextSMS = 1;
            if (bankErrDialog()) {
                /*************最终短信与支付密码页*****************/
                if (payPage()) {
                    ChatClient.msg("<YZF>{'header':'" + ChatClient.M_TRANSFERFINISH_P + "'}</YZF>");
                    /************判定交易结果****************/
                    sleep(1000);
                    payResultPage();
                    return;
                } else {
                    showMsg("汇款账单错误");
                    return;
                }
            }
        }
    }

    /**
     * 选择银行
     *
     * @throws UiObjectNotFoundException
     */
    private boolean selectBank() throws UiObjectNotFoundException {
        BankOrder bankOrder = list.get(0);
        while (true) {
            UiObject mET_bankName = mDevice.findObject(new UiSelector().className("android.widget.EditText").resourceId("demo-input-3"));
            if (mET_bankName.exists()) {
                showMsg("点击银行名框");
                mET_bankName.click();
                sleep(ChatClient.overtime_3);
                break;
            }
        }
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_3) {
                showMsg("银行存在");
                return true;
            }
            UiObject mET_bankName = mDevice.findObject(new UiSelector().className("android.widget.EditText").resourceId("demo-input-3"));
            if (mET_bankName.exists()) {
                String bankName = mET_bankName.getText();
                if (StringUtils.isEmpty(bankName)) {
                    showMsg("点击银行名框");
                    mET_bankName.click();
                    sleep(ChatClient.overtime_3);
                }
            }
            UiObject mET_bank_search = mDevice.findObject(new UiSelector().resourceId("com.yt.hxmb50.launcher:id/rl_search").index(0));
            if (mET_bank_search.exists()) {
                showMsg("点击银行搜索框");
                mET_bank_search.click();
                sleep(ChatClient.overtime_2);
                break;
            }
        }
        //选择银行
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_15) {
                String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "'," +
                        "'phoneModel':'华夏银行'," +
                        "'info':'银行名错误'";
                String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':1," +
                        "'type':1";
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_SEND_TRADE_RESULT_P + "'," + json + "," + mobileD +
                        "}</YZF>");
                //删除处理过的订单
                mapDelete(list.get(0).getOrder());
                getmap();
                sleep(ChatClient.overtime_2);
                backTransferHome();
                return false;
            }
            UiObject mET_search = mDevice.findObject(new UiSelector().resourceId("com.yt.hxmb50.launcher:id/et_search").index(1));
            if (mET_search.exists()) {
                showMsg("填入:" + bankOrder.getBankName());
                mET_search.setText(bankOrder.getBankName());
                sleep(ChatClient.overtime_3);
                UiObject mTV_bank_item = mDevice.findObject(new UiSelector().text(bankOrder.getBankName()).resourceId("com.yt" +
                        ".hxmb50.launcher:id/textview"));
                if (mTV_bank_item.exists()) {
                    showMsg("选择:" + bankOrder.getBankName());
                    mTV_bank_item.click();
                    sleep(ChatClient.overtime_3);
                    break;
                }
            }
        }
        return true;
    }

    /**
     * 最终短信与支付密码页
     */
    private boolean payPage() throws UiObjectNotFoundException {
        showMsg("第" + isNextSMS + "次获取短信");
        if (isNextSMS > 3) {
            ChatClient.timer(LogToFile.getMethodName(), "验证码多次错误");
        }
        if (isNextSMS > 1) {
            ChatClient.begintime = System.currentTimeMillis();//开始时间
            while (true) {
                long nowtime = System.currentTimeMillis();
                if ((nowtime - ChatClient.begintime) > ChatClient.overtime_6) {
                    showMsg("未返回...");
                    break;
                }
                UiObject uiObject = mDevice.findObject(new UiSelector().text("确认").className("android.widget.Button"));
                UiObject mLL_close = mDevice.findObject(new UiSelector().index(0).resourceId("com.yt.hxmb50.launcher:id/closeLL"));
                if (mLL_close.exists()) {
                    showLog("关闭短信弹窗");
                    mLL_close.click();
                    sleep(ChatClient.overtime_1);
                }
                if (uiObject.exists()) {
                    showMsg("点击跨行汇款中确认");
                    uiObject.click();
                    bankErrDialog();
                    break;
                }
            }
            sleep(ChatClient.overtime_1);
        }
        /******跳转汇款提交页********/
        //无卡短信验证码处理
        if (!user.getUseType().equals("1")) {
            ChatClient.begintime = System.currentTimeMillis();//开始时间
            while (true) {
                long nowtime = System.currentTimeMillis();
                if ((nowtime - ChatClient.begintime) > ChatClient.overtime_30) {
                    String errStr = "支付页支付密码识别超时";
                    showMsg(errStr);
                    ChatClient.timer(LogToFile.getMethodName(), ChatClient.keyIdentificationErr);
                    return false;
                }
                UiObject uiObject = mDevice.findObject(new UiSelector().text("请输入短信验证码").resourceId("com.yt.hxmb50.launcher:id/tv_title"));
                if (uiObject.exists()) {
                    showMsg("获取短信验证码");
                    ChatClient.addWorkTime(ChatClient.overtime_60);
                    if (isNextSMS > 1) {
                        sleep(ChatClient.overtime_8);
                    }
                    requestSMS();
                    break;
                }
            }

            ChatClient.begintime = System.currentTimeMillis();//开始时间
            while (true) {
                long nowtime = System.currentTimeMillis();
                if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                    break;
                }
                UiObject object = mDevice.findObject(new UiSelector().resourceId("com.yt.hxmb50.launcher:id/smsCodeErrorMsgTV").text("验证码不正确"));
                if (object.exists() || StringUtils.isEmpty(ChatClient.smsCode.getSmscode())) {
                    showMsg("验证码不正确");
                    isNextSMS += 1;
                    payPage();
                    return true;
                }
            }
        }
        /*****************真机转账密码验证弹窗**********************/
        sleep(ChatClient.overtime_6);
        while (true) {
            UiObject uiObject = mDevice.findObject(new UiSelector().resourceId("com.yt.hxmb50.launcher:id/titleInPwdAlerTV").text("请输入付款卡密码"));
            if (uiObject.exists()) {
                showMsg("输入支付密码");
                setClickNum(user.getBankpwd(), false);
                break;
            }
        }
        sleep(ChatClient.overtime_5);

        /********短信验证码错误重新请求填入*********/
        if (isNextSMS < 3) {
            ChatClient.begintime = System.currentTimeMillis();
            while (true) {
                long nowtime = System.currentTimeMillis();
                if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                    showMsg("短信错误弹窗超时");
                    break;
                }
                UiObject uiObject = mDevice.findObject(new UiSelector().resourceId("com.yt.shareres:id/titleTV"));
                UiObject uiObject1 = mDevice.findObject(new UiSelector().resourceId("com.yt.shareres:id/contentTV"));
                UiObject uiObject2 = mDevice.findObject(new UiSelector().resourceId("com.yt.shareres:id/rightOkTV"));
                String text = "";
                if (uiObject.exists() && uiObject1.exists() && uiObject2.exists()) {
                    text = uiObject2.getText();
                    if (text.equals("")) {
                        text = uiObject2.getContentDescription();
                    }
                }
                if (text.contains("动态验证未通过")) {
                    showMsg("短信错误弹窗：" + isNextSMS);
                    mDevice.pressBack();
                    sleep(ChatClient.overtime_2);
                    isNextSMS += 1;
                    return payPage();
                }
            }
        }
        boolean errDialog = bankErrDialog();
        return errDialog;
    }


    /**
     * 支付结果页处理
     */
    private void payResultPage() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtimeLogin) {
                showMsg("汇款结果页超时");
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.errorStr);
                return;
            }
            UiObject uiObject = mDevice.findObject(new UiSelector().className("android.webkit.WebView").index(0));
            UiObject uiObject1 = uiObject.getChild(new UiSelector().className("android.view.View").index(0));
            UiObject uiObject2 = uiObject1.getChild(new UiSelector().className("android.view.View").index(1));
            if (uiObject2.exists()) {
                String text = uiObject2.getContentDescription();
                if (StringUtils.isEmpty(text)) {
                    text = uiObject2.getText();
                }
                showMsg(text);
                sendResultInfo(text);
                sleep(1000);
                while (true) {
                    UiObject mTV = mDevice.findObject(new UiSelector().text("继续转账").className("android.view.View"));
                    if (mTV.exists()) {
                        Rect bounds = mTV.getBounds();
                        showMsg("点击《继续转帐》");
                        mDevice.click(bounds.centerX() + 120, bounds.centerY());
                        return;
                    }
                }
            }
        }
    }


    /**
     * 无卡机请求T端短信验证码
     */
    private void requestSMS() throws UiObjectNotFoundException {
        ChatClient.requestSMSCode(user.getUserName(), user.getBankId());
        sleep(ChatClient.overtime_2);
        if (ChatClient.smsCode != null) {
            showMsg("收到短信验证码：" + ChatClient.smsCode.getSmscode());
            if (StringUtils.isEmpty(ChatClient.smsCode.getSmscode())) {
                showMsg("短信为null");
                return;
            }
            while (true) {
                UiObject uiObject = mDevice.findObject(new UiSelector().index(1).resourceId("com.yt.hxmb50.launcher:id/inputSmsCodeET"));
                if (uiObject.exists()) {
                    UiObject bankPwb = uiObject.getFromParent(new UiSelector().className("android.widget.EditText").index(1));
                    if (bankPwb.exists()) {
                        if (ChatClient.smsCode.getTelephone().equals(user.getUserName())) {
                            showMsg("填写验证码：" + ChatClient.smsCode.getSmscode());
                            bankPwb.setText("");
                            bankPwb.setText(ChatClient.smsCode.getSmscode());
                            return;
                        }
                    }
                }
            }
        } else {
            showMsg("第" + isNextSMS + "条未收到短信");
        }
    }

    /**
     * 遇见明显错误无法完成，直接上报错误，从新开始请求订单
     *
     * @param failInfo
     * @throws UiObjectNotFoundException
     */
    private void failErr(String failInfo) {
        sendResultInfo(failInfo);
        backTransferHome();
    }

    /**
     * 处理输入金额，错误从新输入
     *
     * @throws UiObjectNotFoundException
     */
    private void putMoney() throws UiObjectNotFoundException {
        boolean flag = true;
        while (flag) {
            UiObject mET_money = mDevice.findObject(new UiSelector().resourceId("amount_trans").index(1));
            if (mET_money.exists()) {
                showMsg("输入金额");
                switch (moneyError(mET_money)) {
                    case 0:
                        showMsg("填写汇款金额");
                        mET_money.legacySetText("");
                        sleep(1000);
                        clickMoneyNum(mET_money);
                        sleep(1000);
                        break;
                    case 1:
                        showMsg("输入金额成功");
                        flag = false;
                        break;
                    case 2:
                        showMsg("输入金额错误");
                        sleep(ChatClient.overtime_1);
                        mDevice.click(1010, 1130);
                        sleep(ChatClient.overtime_1);
                        break;
                }
            }
        }
    }

    /**
     * 判断输入金额是否正确
     *
     * @param mET 金额输入框
     * @return 0:直接输入 1：输入正确 2：删除后输入
     * @throws UiObjectNotFoundException
     */
    private int moneyError(UiObject mET) throws UiObjectNotFoundException {
        String money = mET.getText().trim();
        money = money.replaceAll(",", "");
        showMsg("输入金额：" + money);
        if (StringUtils.isEmpty(money)) {
            return 0;
        } else {
            if (Double.parseDouble(money) == Double.parseDouble(list.get(0).getMoney())) {
                return 1;
            } else {
                return 2;
            }
        }
    }

    private void clickMoneyNum(UiObject mET) {
        String money = list.get(0).getMoney();
        sleep(ChatClient.overtime_2);
        setClickNum(money, true);
        /********收起键盘********/
    }

    /**
     * 账单信息错误直接返回首页
     *
     * @return
     * @throws UiObjectNotFoundException
     */
    private boolean bankErrDialog() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_10) {
                showMsg("信息错误弹窗超时");
                return true;
            }
            UiObject uiObject = mDevice.findObject(new UiSelector().resourceId("com.yt.shareres:id/titleTV"));
            UiObject uiObject1 = mDevice.findObject(new UiSelector().resourceId("com.yt.shareres:id/contentTV"));
            UiObject uiObject2 = mDevice.findObject(new UiSelector().resourceId("com.yt.shareres:id/rightOkTV"));
            UiObject uiObject3 = mDevice.findObject(new UiSelector().resourceId("com.yt.hxmb50.launcher:id/pwdErrorMsgTV").index(0));

            String text = "";
            String text1 = "";
            if (uiObject.exists() && uiObject1.exists() && uiObject2.exists()) {
                showMsg("信息错误弹窗");
                text = uiObject1.getText();
                text1 = uiObject2.getText();

                if (text.contains("今日已通过手机银行累计向该账号汇款") && text1.equals("继续转账")) {
                    showMsg("同账户多次转账");
                    uiObject2.click();
                    return true;
                }

                if (text.equals("请选择收款银行")) {
                    text += ",银行卡前六位错误";
                    showMsg("弹窗错误：" + text);
                    failErr(text);
                    return false;
                }
                if (text.contains("请选择收款银行") || text.contains("对方行已拒绝")|| text.contains("账号不存在")) {
                    text += ",银行卡号错误";
                    showMsg("弹窗错误：" + text);
                    failErr(text);
                    return false;
                }
                if (uiObject3.exists()) {
                    showMsg("输入支付密码错误");
                    sendResultInfo(uiObject3.getText());
                    failErr(text);
                    return false;
                }
            }
        }
    }

    /**
     * 上报转账结果
     ***/
    private void sendResultInfo(String info) {
        if (Constants.getStr(info) == 0) {
            DecimalFormat formater = new DecimalFormat("#0.##");
            sumMoney = formater.format(Double.parseDouble(sumMoney) - Double.parseDouble(list.get
                    (0).getMoney()));
            showMsg("本地保存余额...");
            String sumMoneyFile = user.getUserName() + bankname + "_sumMoney.txt";
            FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
        }
        String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "'," +
                "'phoneModel':'华夏银行'," + "'info':'" + info + "'";
        String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "'," +
                "'state':" + Constants.getStr(info) + ",'type':1";
        if (Constants.getStr(info) == 4) {
            ChatClient.msg("<YZF>{'header':'" + ChatClient.S_CONFIRM_TRADE_RESULT_C + "'," + json + ","
                    + mobileD + "}</YZF>");
        } else {
            ChatClient.msg("<YZF>{'header':'" + ChatClient.M_SEND_TRADE_RESULT_P + "'," + json + ","
                    + mobileD + "}</YZF>");
        }
        //删除处理过的订单
        mapDelete(list.get(0).getOrder());
        getmap();
    }


    /**
     * 界面卡死转圈解决
     *
     * @throws RemoteException
     * @throws UiObjectNotFoundException
     */
    private void handlePageStuck() throws RemoteException, UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_15) {
                showMsg("=====华夏转账界面卡死点击运行应用键=====");
                mDevice.pressRecentApps();
                sleep(2000);
                while (true) {
                    UiObject mTV_app_name;
                    mTV_app_name = mDevice.findObject(new UiSelector().resourceId("com.android.systemui:id/activity_description")
                            .text("华夏银行"));
                    if (mTV_app_name.exists()) {
                        showMsg("=====华夏汇款业务界面卡死点击底部从新打开华夏银行=====");
                        mTV_app_name.click();
                        break;
                    }
                }
                sleep(2000);
            }
            UiObject zhuanzhang = null;
            UiObject money = null;
            zhuanzhang = mDevice.findObject(new UiSelector().resourceId("nameInput"));
            money = mDevice.findObject(new UiSelector().text("当前余额").className("android.widget.TextView"));
            if (zhuanzhang.exists() || money.exists()) {
                break;
            }
        }
    }

    /**
     * 模拟点击数字键盘
     */
    public void setClickNum(String clickNum, boolean isback) {
        char[] num = "1234567890.".toCharArray();//char数组
        char[] bankNum = clickNum.toCharArray();//char数组
        for (int j = 0; j < bankNum.length; j++) {
            for (int i = 0; i < num.length; i++) {
                if (num[i] == bankNum[j]) {
                    showLog("点击---" + j);
                    mDevice.click(xy_123[i][0], xy_123[i][1]);
                    sleep(1000);
                    break;
                }
            }
        }
        if (isback) {
            mDevice.pressBack();
        }
    }

    /**
     * 点击左上角返回上页
     */
    private void backTransferHome() {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_3) {
                ChatClient.begintime = System.currentTimeMillis();
                showMsg("返回上一层");
                mDevice.pressBack();
                ChatClient.begintime = System.currentTimeMillis();//开始时间
            }
            UiObject mV = mDevice.findObject(new UiSelector().text("新收款人").className("android.view.View"));
            if (mV.exists()) {
                showMsg("返回转账首页");
                break;
            }
        }
    }


    private void showLog(String msg) {
        Log.i("华夏银行" + "==", "===《" + msg + "》===");
    }

    private void showMsg(String msg) {
        LogToFile.showLog("华夏银行", msg);
    }
}